package servlet.classes ;

import com.alibaba.fastjson.JSONObject;
import utils.JdbcUtil;
import utils.ResultData;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 *      类别信息添加
 */
@WebServlet(urlPatterns = "/classAdd")
public class ClassAdd extends HttpServlet {
    JdbcUtil jdbc = new JdbcUtil();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String name =req.getParameter("classesname");
        String remark =req.getParameter("remark");
        Connection connection = jdbc.getConnection();

        String sql = "insert into classes_table(classesname,remark) value(?,?)";

        try {
            PreparedStatement preparedStatement =connection.prepareStatement(sql);
            ResultData resultData = null;

            if (name != null && name.trim().length() !=0){
                preparedStatement.setString(1,name);
            }else {
                 resultData = ResultData.buildMsg(1,"姓名不能为空");
            }
            if (remark != null && remark.trim().length() !=0){
                preparedStatement.setString(2,remark);
            }else {
                resultData = ResultData.buildMsg(1,"备注不能为空");
            }

            int i = preparedStatement.executeUpdate();

            if (i > 0){
                resultData = ResultData.success();
            }else {
                resultData = ResultData.fail();
            }

            Object o = JSONObject.toJSON(resultData);
            resp.getWriter().println(o.toString());

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
